using System;
using System.Data;
using System.IO;
using System.Collections.Generic;
using System.Text;

using Widgetsphere.Generator.Common.Util;
using Widgetsphere.Generator.Common.Logging;
using System.Xml.Serialization;

namespace Widgetsphere.Generator.Common.GeneratorFramework
{
	public class AddinAppData
	{
		#region Class Members

		private const string DATA_FILE_NAME = "addInStore.xml";
		private const string COMPANY_FOLDER = "Widgetsphere";
		private const string REG_LOCATION = @"Software\Widgetsphere\VSCodeTools";
		private const string REG_INSTALLDIR_PROPERTY = "installdir";

		private static AddinAppData _instance;

		private FileInfo _addinDataStoreFile;
		private AddinProperties _addInProperties;

		#endregion

		#region Constructors

		static AddinAppData()
		{
			_instance = new AddinAppData();
		}

		private AddinAppData()
		{
			string appDataFolder = StringHelper.EnsureDirectorySeperatorAtEnd(System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData));
			string fullFileName = string.Format("{0}{1}/{2}", appDataFolder, COMPANY_FOLDER, DATA_FILE_NAME);

			_addinDataStoreFile = new FileInfo(fullFileName);
			if (_addinDataStoreFile.Exists)
			{
				XmlSerializer serializer = new XmlSerializer(typeof(AddinProperties));
				TextReader tr = new StreamReader(_addinDataStoreFile.FullName);
				_addInProperties = (AddinProperties)serializer.Deserialize(tr);
				tr.Close();
			}
			else
			{
				_addInProperties = new AddinProperties();
				_addInProperties.ExtensionDirectory = RegistryHelper.GetLocalMachineRegistryValue(REG_LOCATION, REG_INSTALLDIR_PROPERTY);
				this.Save();
			}
		}

		#endregion

		#region Properties

		private AddinProperties Properties
		{
			get { return _addInProperties; }
		}

		public static AddinAppData Instance
		{
			get { return _instance; }
		}

		public string ExtensionDirectory
		{
			get
			{
				string retval = Properties.ExtensionDirectory;

				//Default
				if (retval == null)
					retval = RegistryHelper.GetLocalMachineRegistryValue(REG_LOCATION, REG_INSTALLDIR_PROPERTY);
				return retval;
			}
		}

		public void Save()
		{
			try
			{
				if (!_addinDataStoreFile.Directory.Exists)
					_addinDataStoreFile.Directory.Create();

				XmlSerializer serializer = new XmlSerializer(typeof(AddinProperties));
				TextWriter tw = new StreamWriter(_addinDataStoreFile.FullName);
				serializer.Serialize(tw, Properties);
				tw.Close();

			}
			catch (Exception ex)
			{
				WSLog.LogError(ex);
			}
		}

		#endregion

	}
}